package hello;

import java.util.*;
import javax.persistence.*;


public class HelloWorld
{
	public static void main(String[] args) 
	{
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("helloworld");
				
		EntityManager em=emf.createEntityManager();
		EntityTransaction tx=em.getTransaction();
		out(emf);out(em);out(tx);
		tx.begin();
		
		Message message=new Message("Hello World!");
		em.persist(message);
		
		tx.commit();
		em.close();
		
		EntityManager newEm=emf.createEntityManager();
		EntityTransaction newTx=newEm.getTransaction();
		newTx.begin();
		
		List messages=newEm.createQuery("select m from Message m order by m.text asc").getResultList();
		
		System.out.println(messages.size()+" message(s) found");
		for(Object m : messages)
		{
			Message loadedMsg=(Message)m;
			System.out.println(loadedMsg.getText());
		}
		
		newTx.commit();
		newEm.close();
		
		emf.close();
	}
	
	public static void out(Object obj)
	{
		System.out.println("-------"+obj.getClass().getName());
	}
}